package com.lebang.controller.api;

import com.alibaba.fastjson.JSONObject;
import com.lebang.aop.Sessionid;
import com.lebang.component.AsyncsComponent;
import com.lebang.component.RedisClient;
import com.lebang.domain.AppResoure;
import com.lebang.domain.LogoutRecord;
import com.lebang.domain.UploadImgRecord;
import com.lebang.entity.LbbAppVersion;
import com.lebang.entity.LbbFloatSwitch;
import com.lebang.entity.RequestHeaders;
import com.lebang.entity.member.LbbMember;
import com.lebang.entity.sys.LbbModule;
import com.lebang.example.LbbModuleExample;
import com.lebang.model.RequestUserInfo;
import com.lebang.model.back.ImeiRegister;
import com.lebang.model.enums.Booleans;
import com.lebang.model.enums.Mode;
import com.lebang.model.enums.buss.RewardType;
import com.lebang.model.enums.buss.TradeCategory;
import com.lebang.model.enums.buss.UserStatus;
import com.lebang.service.DownAppService;
import com.lebang.service.LogoutService;
import com.lebang.service.MemberIfMoneyService;
import com.lebang.service.OceanEngineService;
import com.lebang.service.buss.*;
import com.lebang.service.sys.*;
import com.lebang.service.sys.other.AppResoureService;
import com.lebangweb.common.TextUtil;
import com.lebangweb.response.Callback;
import com.lebangweb.response.JsonData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户
 *
 * @author weizx
 * @className ModuleApi
 * @date 2018年7月19日 下午5:40:13
 */
@RestController
public class AppApi {

    @Autowired
    private ModuleService moduleService;


    @Autowired
    private RedisClient redisClient;
    @Autowired
    private AppNoticeService appNoticeService;
    @Autowired
    private AppVersionService appVersionService;
    @Autowired
    private MemberService memberService;

    @Autowired
    private DictService dictService;
    @Autowired
    private AsyncsComponent asyncsComponent;
    @Autowired
    private AppFloatSwitchService appFloatSwitchService;
    @Autowired
    private OceanEngineService oceanEngineService;
    @Autowired
    private WalletService walletService;
    @Autowired
    private LogoutService logoutService;
    @Autowired
    private AppLookCategoryService appLookCategoryService;
    @Autowired
    private AppMainRefreshService appMainRefreshService;
    @Autowired
    private AppStoreCheckService appStoreCheckService;

    @Autowired
    private PkgBlackLogService pkgBlackLogService;

    @Autowired
    private RegisterWhiteImeiService registerWhiteImeiService;
    @Autowired
    private DownAppService downAppService;
    @Autowired
    private  MemberIfMoneyService memberIfMoneyService;

    /**
     * 初始化配置
     *
     * @return
     * @author weizx
     * @date 2018年7月19日 下午5:36:56
     */
    @Sessionid
    @RequestMapping(value = "/config/init", method = {RequestMethod.GET, RequestMethod.POST})
    public JsonData init(HttpServletRequest request, HttpServletResponse response,
                         @RequestParam(value = "params", required = false) String parameter
            , Integer isRoot, String isEmulator, String city) {
        try {

            RequestHeaders requestHeaders = new RequestHeaders(request);
            if (isRoot != null && isRoot == 1) {
                pkgBlackLogService.addLog("root", requestHeaders, "root用户");
            }
            if (isEmulator != null && isEmulator.equals("1")) {
                pkgBlackLogService.addLog("isEmulator", requestHeaders, "模拟器用户");
            }
            ImeiRegister imeiRegister = new ImeiRegister(request);
            String version = requestHeaders.getVersion();
            String appid = requestHeaders.getAppid();
            String appStore = requestHeaders.getAppStore();
            String userid = requestHeaders.getUserid();
            JSONObject data = new JSONObject();
            data.put("strategy", "http://newapi.hotbuybuy.com/business/cooperation");
            data.put("aboutUs", "http://hot.gara.cc/help/3");
            data.put("notice", 0);
            data.put("isCheck", "0");
            oceanEngineService.addImei(imeiRegister, requestHeaders);
            if (!TextUtil.isEmpty(userid)) {
               // memberTradeService.walletClean(userid);
                memberIfMoneyService.check(requestHeaders);
                downAppService.checkHasRecord(requestHeaders);
                String status = memberService.checkMemberByMemberId(userid);
                if (status != null && status.equals(UserStatus.Close.name())) {
                    data.put("appMode", "Debug");
                    return Callback.success("success", "已返回初始化配置！", data);
                }
                if (!TextUtil.isEmpty(status) && status.equals(UserStatus.WaitCheck.name())) {
                    LogoutRecord record = logoutService.selectRecord(userid, null);
                    data.put("record", record);
                }

                LbbMember member = memberService.getMemberByMemberId(userid);
                if (member != null) {
                    memberService.insertMemberHeaderInfo(requestHeaders);
                    memberService.insertDeviceInfo(parameter, member.getMemberId());
                    member.setOsVersion(requestHeaders.getOsVersion());
                    member.setOsv(requestHeaders.getOsv());
                    memberService.updateMemberById(member);
                    data.put("notice", member.getNoticeCount());
                }

            }
            boolean check = memberService.checkImeiAndIpAddr(requestHeaders);
            // 控制版本
            if (check) {
                // data.put("appMode", "Debug");
                data.put("isCheck", "1");
                //   return Callback.success("success", "已返回初始化配置!", data);
            }
            memberService.addLoginRecord(new RequestHeaders(request), city);
            LbbAppVersion v2 = appVersionService.getByInnerCodeAndappStoreAndAppId(Integer.parseInt(version), appStore, appid);
            Mode mode = Mode.Debug;
            if (v2 != null) {
                mode = v2.getAppMode();
            }
            data.put("appMode", mode);
            if (mode.equals(Mode.Beta)) {
                if (check) {
                    if (appStoreCheckService.check(requestHeaders)) {
                        data.put("appMode", Mode.Beta);
                    } else {
                        data.put("appMode", Mode.Debug);
                    }
                }
            }
            return Callback.success("success", "已返回初始化配置！", data);
        } catch (Exception e) {
            e.printStackTrace();
            return Callback.fail("error", e.getMessage());
        }
    }

    /**
     * 初始化配置
     *
     * @return
     * @author weizx
     * @date 2018年7月19日 下午5:36:56
     */
    @Sessionid
    @RequestMapping(value = "/config/init1", method = {RequestMethod.GET})
    public JsonData init1(HttpServletRequest request, HttpServletResponse response, String city) {
        try {

            RequestHeaders requestHeaders = new RequestHeaders(request);
            ImeiRegister imeiRegister = new ImeiRegister(request);
            String version = requestHeaders.getVersion();
            String appid = requestHeaders.getAppid();
            String appStore = requestHeaders.getAppStore();
            String userid = requestHeaders.getUserid();
            JSONObject data = new JSONObject();
            data.put("strategy", "http://newapi.hotbuybuy.com/business/cooperation");
            data.put("aboutUs", "http://hot.gara.cc/help/3");
            data.put("notice", 0);
            oceanEngineService.addImei(imeiRegister, requestHeaders);
            if (!TextUtil.isEmpty(userid)) {
                String status = memberService.checkMemberByMemberId(userid);
                if (status != null && status.equals(UserStatus.Close.name())) {
                    data.put("appMode", "Debug");
                    return Callback.success("success", "已返回初始化配置！", data);
                }
                if (!TextUtil.isEmpty(status) && status.equals(UserStatus.WaitCheck.name())) {
                    LogoutRecord record = logoutService.selectRecord(userid, null);
                    data.put("record", record);
                    // return Callback.fail("201", "用户审核中",data);
                }

                LbbMember member = memberService.getMemberByMemberId(userid);
                if (member != null) {
                    member.setOsVersion(requestHeaders.getOsVersion());
                    member.setOsv(requestHeaders.getOsv());
                    memberService.updateMemberById(member);
                    data.put("notice", member.getNoticeCount());
                }

            }
            boolean check = memberService.checkImeiAndIpAddr(requestHeaders);
            // 控制版本
            if (check) {
                // data.put("appMode", "Debug");
                data.put("isCheck", "1");
                //   return Callback.success("success", "已返回初始化配置!", data);
            }
            memberService.addLoginRecord(new RequestHeaders(request), city);
            LbbAppVersion v2 = appVersionService.getByInnerCodeAndappStoreAndAppId(Integer.parseInt(version), appStore, appid);
            Mode mode = Mode.Debug;
            if (v2 != null) {
                mode = v2.getAppMode();
            }
            data.put("appMode", mode);
            if (mode.equals(Mode.Beta)) {
                if (check) {
                    if (appStoreCheckService.check(requestHeaders)) {
                        data.put("appMode", Mode.Beta);
                    } else {
                        data.put("appMode", Mode.Debug);
                    }
                }
            }
            return Callback.success("success", "已返回初始化配置！", data);
        } catch (Exception e) {
            e.printStackTrace();
            return Callback.fail("error", e.getMessage());
        }
    }

    /**
     * 轮播图
     *
     * @param request
     * @param response
     * @return
     * @author weizx
     * @date 2018年8月7日 下午5:16:39
     */
    //@Sessionid
    @RequestMapping(value = "/config/banner", method = {RequestMethod.GET})
    public JsonData banner(HttpServletRequest request, HttpServletResponse response) {
        RequestHeaders requestHeaders = new RequestHeaders(request);
        try {
            String appStore = requestHeaders.getAppStore();
            List<Map<String, Object>> data = new ArrayList<>(1);
            LbbModuleExample example = new LbbModuleExample();
            example.setOrderByClause("sort desc");
            example.createCriteria().andTypeEqualTo("Banner").andHasDeletedEqualTo(Booleans.False.name());


            List<LbbModule> modules = moduleService.getListByExample(example);

            for (LbbModule m : modules) {
                Map<String, Object> item = new LinkedHashMap<String, Object>();
                if (m.getTitle().equals("每日必赚") && downAppService.checkDoRecord(requestHeaders)) {
                    item.put("icon", "http://imgxy.lbappstore.com/xyunlegend/20200103/837812d2dd8f4b7587913d09035988a1.png");
                    item.put("title", m.getTitle());
                    item.put("subtitle", m.getSubtitle());
                    item.put("label", m.getLabel());
                    item.put("category", "Activity");
                    item.put("params", moduleService.transParams(appStore, "adidear://rotation_lottery"));
                    item.put("_category", m.getfCategory());
                    item.put("_taskid", m.getfTaskid());
                    item.put("_condition", m.getfCondition());
                    item.put("_params", m.getfParams());
                } else {
                    item.put("icon", m.getIcon());
                    item.put("title", m.getTitle());
                    item.put("subtitle", m.getSubtitle());
                    item.put("label", m.getLabel());
                    item.put("category", m.getCategory());
                    item.put("params", moduleService.transParams(appStore, m.getParams()));
                    item.put("_category", m.getfCategory());
                    item.put("_taskid", m.getfTaskid());
                    item.put("_condition", m.getfCondition());
                    item.put("_params", m.getfParams());
                }

                data.add(item);
            }
            return Callback.success("success", "已返回首页轮播图！", data);
        } catch (Exception e) {
            e.printStackTrace();
            return Callback.fail("error", e.getMessage());
        }
    }


    /**
     * 页面轮播文字
     **/
    @PostMapping("/app/getBannerMsg")
    @ResponseBody
    public JsonData getBannerMsg() {
        return Callback.success("200", "成功", appNoticeService.getAllNotice());
    }

    /**
     * 获取用户下载包名
     **/
    @PostMapping("/app/upload/package")
    @ResponseBody

    public JsonData uploadPackage(HttpServletRequest request, String str) {
        asyncsComponent.uploadPackage(new RequestHeaders(request), str);
        return Callback.success("200", "成功", null);
    }

    /**
     * app端用接口
     **/
    @PostMapping("/apps/shouye")
    @ResponseBody
    public JsonData find(HttpServletRequest request) {
        try {
            LbbFloatSwitch afs = appFloatSwitchService.getByCategory("shouye");
            return Callback.success("200", "首页导航成功", afs);
        } catch (Exception e) {
            return Callback.fail("200", "首页导航失败", null);
        }

    }

    /**
     * 客服QQ号
     **/
    @PostMapping("/app/friend/qq")
    @ResponseBody
    public JsonData friendqq() {
        try {
            String qq = redisClient.hget("api:sys:config:", "qq");
            return Callback.success("200", "查询成功", qq);
        } catch (Exception e) {
            return Callback.fail("200", "查询失败", "");
        }

    }

    /**
     * 开屏广告开关
     **/
    @PostMapping("/app/open/ad")
    @ResponseBody
    public JsonData open() {
        try {
            return Callback.success("200", "查询成功", dictService.selectByKeyNameInRedis("open_ad_on").getKeyvalue());
        } catch (Exception e) {
            return Callback.fail("200", "查询失败", "");
        }

    }

    /**
     * 开屏广告开关
     **/
    @PostMapping("/app/ad/height")
    @ResponseBody
    public JsonData height() {
        try {
            return Callback.success("200", "查询成功", dictService.selectByKeyNameInRedis("csj_ad_height").getKeyvalue());
        } catch (Exception e) {
            return Callback.fail("200", "查询失败", "");
        }

    }

    @Autowired
    private AppResoureService appResoureService;

    @PostMapping("/app/resoure/list")
    public JsonData list(HttpServletRequest request, Integer openAddress) {
        if (TextUtil.isEmpty(openAddress)) {
            return Callback.fail("success", "参数非法");
        }
        RequestHeaders headers = new RequestHeaders(request);

        Integer all = walletService.cash(headers.getUserid(), headers.getAppid(), TradeCategory.Income.name(), RewardType.Cash.name(), null, null);
        List<AppResoure> list = appResoureService.selectListByUserInfo(new RequestHeaders(request), openAddress);
        for (AppResoure v : list) {
            v.setList(appLookCategoryService.reviewResoure(v.getList(), headers, all));
        }

        return Callback.success("success", "查询成功", list);
    }

    @Autowired
    private UploadImgRecordService uploadImgRecordService;

    @PostMapping("/app/member/upload/rank")
    public JsonData upload(HttpServletRequest request, String url) {
        RequestHeaders requestHeaders = new RequestHeaders(request);
        UploadImgRecord vo = new UploadImgRecord();

        vo.setHasDeleted(0);
        vo.setCreateTime(LocalDateTime.now());
        vo.setModifyTime(LocalDateTime.now());
        vo.setMemberId(requestHeaders.getUserid());
        vo.setAppStore(requestHeaders.getAppStore());
        vo.setVersion(requestHeaders.getVersion());
        vo.setOs(requestHeaders.getOs());
        vo.setOsv(requestHeaders.getOsv());
        vo.setIpAddr(requestHeaders.getIpAddr());
        vo.setMacAddr(requestHeaders.getMacAddr());
        vo.setImei(requestHeaders.getImei());
        vo.setImgUrl(url);
        uploadImgRecordService.insertModel(vo);
        return Callback.success("success", "查询成功", null);
    }

    @PostMapping("/app/refresh/main")
    public JsonData refresh(HttpServletRequest request) {
        return Callback.success("success", "查询成功", appMainRefreshService.selectByAppStore(new RequestHeaders(request)));
    }

    @PostMapping("/app/checkip")
    @Sessionid
    public JsonData checkIp(HttpServletRequest request) {
        RequestUserInfo requestUserInfo = new RequestUserInfo(request);

        if (registerWhiteImeiService.getImei(requestUserInfo.getImei())) {
            return Callback.success("success", "进入首页成功");
        }

        if (TextUtil.isEmpty(requestUserInfo.getMemberId())) {
            return Callback.success("success", "进入首页成功");
        }
        Integer checkIpNum = dictService.selectIntByKeyName("check_ip_num");
        Integer checkIpHourTime = dictService.selectIntByKeyName("check_ip_hour_time");
        LocalDateTime end = LocalDateTime.now();
        LocalDateTime star = end.minusHours(checkIpHourTime.longValue());
        if (memberService.checkIpByMemberId(star, end, requestUserInfo)) {
            return Callback.success("success", "进入首页成功");
        }
        if (memberService.checkIpNumByHour(star, end, checkIpNum, requestUserInfo)) {
            return Callback.fail("fail", "您当前网络环境被系统限制，请联系客服处理");
        }
        return Callback.success("success", "进入首页成功");
    }

    @Value("${info.open_text}")
    private String text;
    @Value("${info.open_title2}")
    private String text2;
    @Value("${info.open_title1}")
    private String title;


    @PostMapping("/app/open/title")
    public JsonData title(HttpServletRequest request) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("text", text);
        jsonObject.put("title", title);
        jsonObject.put("text1", text2);
        return Callback.success("success", "查询成功", jsonObject);
    }

}
